#!/usr/bin/env python

import sys
import operator
from platform import system
from paPlotter import Plotter, unformatTime, cmpTime
from paUtils import *
from shelve import open as shopen
from pylab import ion, ioff, savefig, title, figure, gca, close
if system()=="Windows":
    from keypress import funkeypress
else:
    from terminalfile import TerminalFile
    tty0 = TerminalFile(sys.stdin)
from optparse import OptionParser
usage = "usage: %prog [options] arg"
parser = OptionParser(usage)
parser.add_option("-f",
                  "--file",
                  action = "store",
                  type = "string",
                  dest = "logfile")
parser.add_option("-b",
                  "--baselines",
                  action = "store",
                  type = "string",
                  dest = "baselines_str")
(options, args) = parser.parse_args()
logfile = options.logfile
baselines = options.baselines_str.split(",")
for i in range(len(baselines)):
    baselines[i] = int(baselines[i])

print "Reading pad file: ",logfile

try:
    open(logfile)
except IOError:
    print "File does not exist!"
    sys.exit()

padPlotter = Plotter()
padfile = shopen(logfile)

valid = []
for k in padfile.keys():
    if k != "start":
        valid.append([k,unformatTime(k),list(padfile[k])])
        #print k

valid.sort(cmpTime, key=operator.itemgetter(1))

for i in range(len(valid)):
    valid[i][2].append([])
    valid[i][2].append([])
    temp = {}
    for j in range(7):
        thefit = getPhaseFit(dewrap(valid[i][2][2][j]))
        valid[i][2][4].append(thefit[1])
        valid[i][2][5].append(thefit[0])
        temp[j] = thefit[0]
    padPlotter.addPhasePoint(temp)
    
print "**************************************************"
print "'o' goes to the previous integration."
print "'p' goes to the next integration."
print "Space key goes to a specific integration."
print "'s' saves the figure as a png."
print "'q' terminates the loop."
print "There are a total of "+str(len(valid))+" integrations."
print "**************************************************"
print

fig = gca()
ion()
last = len(valid) - 1
i = 0
while True:
    if system()=="Windows":
        cmd = funkeypress()
    else:
        cmd = tty0.getch()
    if cmd==111 or cmd=='o': # o
        if i == 0:
            print "Cycling to last integration...",
            i = last
        else:
            print "Plotting previous integration...",
            i -= 1
    elif cmd==112 or cmd=='p': # p
        if i == last:
            print "Cycling to first integration...",
            i = 0
        else:
            print "Plotting next integration...",
            i += 1
    elif cmd==32 or cmd==' ': # space
        integ = raw_input('Go to integration: ')
        if int(integ) not in range(len(valid)):
            print integ+" not within range."
            print "Plotting integration...",
        else:
            print "Going to integration...",
            i = int(integ)
    elif cmd==115 or cmd=='s': # s
        figname = raw_input('Filename: ')
        savefig(figname)
    elif cmd==113 or cmd=='q': # q
        close()
        print "Terminating."
        break
    else:
        continue
    print valid[i][0]
    print "Integration "+str(i)+" of "+str(len(valid))+"."
    print
    fig.set_title(logfile+" --> "+valid[i][0])
    padPlotter.loadData(valid[i][2])
    padPlotter.plotBaselines(figure(1),baselines,i)
    #padPlotter.plotData(figure(1),[0,1,2,3,4,5,6])
    
